import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'
import { message } from 'antd'
import storage from '@/utils/storage'
interface ResponseData<T> {
  code: number
  data: T
  msg: string
  status: number
}

const service = axios.create({
  baseURL: process.env.REACT_APP_BASE_API,
  timeout: 6000
})

// 请求拦截
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = storage.getStorage('token')

    // 获取用户token，用于校验
    if (token) {
      ;(config as any).headers.token = token
    }
    return config
  },
  (error: AxiosError) => Promise.reject(error)
)

// 响应拦截
service.interceptors.response.use(
  (response: AxiosResponse<ResponseData<any>>) => {
    return response.data.data
  },
  (error: AxiosError) => {
    message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
